<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { addFreeData, updateFreeData } from '/@/api/free/data';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let tableLabel = '';
      let tableName = '';

      const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
        labelWidth: 90,
        schemas: [],
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        setProps({
          schemas: data.freeProp.formScheme,
        }).then(() => {
          resetFields();
          setDrawerProps({ confirmLoading: false });
          isUpdate.value = !!data?.isUpdate;

          if (unref(isUpdate)) {
            setFieldsValue({
              ...data.record,
            });
          }
        });
        tableLabel = data.freeProp.tableInfo.tableLabel;
        tableName = data.freeProp.tableInfo.tableName;
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑') + tableLabel);

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            updateFreeData(tableName, values).then(() => {
              closeDrawer();
              emit('success', false, values);
            });
          } else {
            addFreeData(tableName, values).then((id) => {
              values.id = id;
              closeDrawer();
              emit('success', false, values);
            });
          }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
